package FillMythMetadataTheTVDB;
use FillMythMetadataUtilities;
use strict;
use warnings;

#this API key can easily be given if you register at www.thetvdb.com.
#do not use this API key for other scripts!
my $thetvdb_API_key = "6770D263BF045B96";

my $THETVDB = "www.thetvdb.com";

sub search_the_tv_db_for_series
{
	my $series = $_[0];
	print "Searching THE-TV-DB for series '$series'\n";
	my $series_for_url = $series;
	my $scontent = FillMythMetadataHttpCaller::get_http_response("http://".$THETVDB."/api/GetSeries.php?seriesname=$series_for_url");
	my $series_id = "";
	my $plot = "";
	my $tvdb_series_name = "";
	
	my $best_similarity = 1000000;
	#? marks the regexp as ungreedy (don't look for the longest, look for the first - which is actually IS a greedy algorithm...)
	#"gi" at the end makes it recursive
	#while ($scontent =~ m/<seriesid>(.+?)<\/seriesid>.*?<seriesname>(.+?)<\/seriesname>.*?<banner>(.+?)<\/banner>.*?<overview>(.+?)<\/overview>/gi)
	while ($scontent =~ m/<series>.*?<seriesid>(.+?)<\/seriesid>.*?<seriesname>(.+?)<\/seriesname>(.+?)<\/series>/gi)
	{
		my $temp_series_id = $1;
		my $temp_series_name = $2;
		my $current_similarity = FillMythMetadataUtilities::levenshtein($series, $temp_series_name);
		#print "++++++++++++++++++++++++++++++++++++++++++\n";
		#print "Best similarity: $best_similarity Current: $current_similarity\n";
		if ($current_similarity < $best_similarity)
		{
			if ($series_id eq "")
			{
				print "Found a possible match for '$series' as '$temp_series_name' (ID $temp_series_id)\n";
			}
			else
			{
				print "Found a better possible match for '$series' as '$temp_series_name' (ID $temp_series_id)\n";
			}
			$best_similarity = $current_similarity;
			$series_id = $1;
			$tvdb_series_name = $2;
			my $rest_of_the_data = $3;


			if ($rest_of_the_data =~ m/<overview>(.+?)<\/overview>/i){$plot = $1;}
			else {$plot = "";}
		}
		#print "++++++++++++++++++++++++++++++++++++++++++\n";
	}
	if ((length $series_id) > 0)
	{
		print "Found ID '$series_id' for series '$series' at THE-TV-DB.\n";
		return ($series_id);
	}
	else
	{
		print "Can not locate series '$series' in THE-TV-DB.\n";
		return ("");
	}
}

sub get_series_meta_data
{
	my $series_id = $_[0];
	my $series_name = $_[1];
	
	my $actual_show_name;
	if ((length $series_id) eq 0)
	{
		$series_id = search_the_tv_db_for_series($series_name);
	}
	if ((length $series_id) gt 0)
	{
		#print "the-tv-db info found '$series_name' at '$folder_path'.\n";
		my $scontent = FillMythMetadataHttpCaller::get_http_response("http://".$THETVDB."/api/".$thetvdb_API_key."/series/".$series_id."/en.xml");
		my $content_rating = "NR";
		my $imdb;
		my $poster = "";
		my $banner = "";
		my $fanart = "";
		my $plot = "";
		
		if ($scontent =~ m/<ContentRating>(.+)<\/ContentRating>/i)
		{
			$content_rating = $1;
		}
		if ($scontent =~ m/<IMDB_ID>(.+)<\/IMDB_ID>/i)
		{
			$imdb = $1;
			$imdb =~ s/tt//g;
		}
		if ($scontent =~ m/<overview>(.+)<\/overview>/i)
		{
			$plot = $1;
		}
		if ($scontent =~ m/<seriesname>(.+)<\/seriesname>/i)
		{
			$actual_show_name = $1;
		}
		if ($scontent =~ m/<banner>(.+)<\/banner>/i)
		{
			$banner = "http://".$THETVDB."/banners/".$1;
		}
		if ($scontent =~ m/<fanart>(.+)<\/fanart>/i)
		{
			$fanart = "http://".$THETVDB."/banners/".$1;
		}
		if ($scontent =~ m/<poster>(.+)<\/poster>/i)
		{
			$poster = "http://".$THETVDB."/banners/".$1;
		}
		
		
		if ((length $series_name) eq 0)
		{#if the name was not provided, we'll take it from the response. This will help us cache the series ID (see the call of 'get_series_meta_data' function).
			$series_name = $actual_show_name;
		}
		if ($content_rating eq "") 
		{
			$content_rating = "NR"
		}
		
		return ($series_id, $series_name, $poster, $banner, $fanart, $plot, $actual_show_name, $content_rating, $imdb);
	}
	
	return ("", "", "", "", "", "", "");
}

sub get_season_banners
{
	my $series_id = $_[0];
	my $season = $_[1];

	if (((length $series_id) gt 0) && ((length $season) gt 0))
	{
		#http://www.thetvdb.com/api/6770D263BF045B96/series/80348/banners.xml
		my $seacontent = FillMythMetadataHttpCaller::get_http_response("http://".$THETVDB."/api/".$thetvdb_API_key."/series/".$series_id."/banners.xml");
		
		while ($seacontent =~ m/<Banner>.*?<id>(.+?)<\/id>.*?<BannerPath>(.+?)<\/BannerPath>.*?<BannerType>(.+?)<\/BannerType>.*?<Language>en<\/Language>.*?<Season>(.+?)<\/Season>.*?<\/Banner>/gi)
		{	
			if (($4 eq $season) && ($3 eq "season")) {return ("http://".$THETVDB."/banners/".$2);}
		}
			
		
	}
	
	return ("");
}

sub create_episode_url
{
	my $series_id = $_[0];
	my $season = $_[1];
	my $episode = $_[2];
	
	return "http://".$THETVDB."/api/".$thetvdb_API_key."/series/".$series_id."/default/".$season."/".$episode."/en.xml";
}

sub create_episode_url_by_episode_id
{
	my $episode_id = $_[0];
	#http://www.thetvdb.com/api/6770D263BF045B96/episodes/54545/en.xml
	return "http://".$THETVDB."/api/".$thetvdb_API_key."/episodes/".$episode_id."/en.xml";
}

sub get_episode_meta_data
{
	my $series_id = $_[0];
	my $season = $_[1];
	my $episode = $_[2];
	
	my $episode_url = create_episode_url($series_id, $season, $episode);
	my $scontent = FillMythMetadataHttpCaller::get_http_response($episode_url);
	#if the episode is 0 (a pilot?), and there is no content, we'll try the first episode
	if (((length $scontent) eq 0) && ($episode eq '0'))
	{
		$episode_url = create_episode_url($series_id, $season, "1");
		$scontent = FillMythMetadataHttpCaller::get_http_response($episode_url);
	}
	return parse_episode_content($scontent);
}

my $cached_get_episode_identifies_id = "";
my $cached_get_episode_identifies_content = "";
sub get_episode_meta_data_by_episode_id
{
	my $episode_id = $_[0];
	
	if ($episode_id ne $cached_get_episode_identifies_id)
	{
		my $episode_url = create_episode_url_by_episode_id($episode_id);
		$cached_get_episode_identifies_content = FillMythMetadataHttpCaller::get_http_response($episode_url);
		$cached_get_episode_identifies_id = $episode_id;
	}
	
	return parse_episode_content($cached_get_episode_identifies_content);
}

sub parse_episode_content
{
	my $content = $_[0];
	
	#print "parse_episode_content: ".$content."\n";

	my $episode_name = "";
	my $plot = "";
	my $rating = 0;
	my $poster = "";
	my $director = "";
	my $air_date = 0;
	my $episode_number = "";
	my $season_number = "";
	my $series_id = "";
	my $episode_id = "";
	my $imdb_id = "";
	
	if ($content =~ m/<EpisodeName>(.+)<\/EpisodeName>/i)
	{
		$episode_name = $1;
	}	
	if ($content =~ m/<Overview>((.|\n|\r|\f)+)<\/Overview>/i)
	{
		$plot = $1;
	}	
	if ($content =~ m/<Rating>(.+)<\/Rating>/i)
	{
		$rating = int($1);
	}	
	if ($content =~ m/<filename>(.+)<\/filename>/i)
	{
		$poster = "http://".$THETVDB."/banners/".$1;
	}
	if ($content =~ m/<Director>(.+)<\/Director>/i)
	{
		$director = $1;
		if ($director =~ m/\|(.+)\|/i)
		{
			$director = $1;
		}
		$director =~ s/\|/, /g;
	
	}
	if ($content =~ m/<FirstAired>(\d+).*<\/FirstAired>/i)#just the year
	{
		$air_date = int($1);
	}	
	if ($content =~ m/<id>(.+)<\/id>/i)
	{
		$episode_id = $1;
	}
	if ($content =~ m/<EpisodeNumber>(.+)<\/EpisodeNumber>/i)
	{
		$episode_number = $1;
	}
	if ($content =~ m/<SeasonNumber>(.+)<\/SeasonNumber>/i)
	{
		$season_number = $1;
	}
	if ($content =~ m/<seriesid>(.+)<\/seriesid>/i)
	{
		$series_id = $1;
	}
	if ($content =~ m/<IMDB_ID>(.+)<\/IMDB_ID>/i)
	{
		$imdb_id = $1;
		$imdb_id =~ s/tt//g;
	}
	
	return ($series_id, $episode_id, $season_number, $episode_number, $episode_name, $plot, $rating, $poster, $director, $air_date, $imdb_id);
}

1;